/**
 * Created by shudong.msd(风骐) on 2016/4/17.
 */
app.factory("searchDataFetcher", ['$http','$timeout','$state',function ($http,$timeout,$state) {

    var comutil = new commUtils();
    var service = {};

    var filterTypes = ['tvTypes','tvNames','terminals','channels','languages','regions','sex','ages','cities','stars'];

    // 默认是总体的过滤项
    var defTotal = ['sex','ages','cities','terminals','channels'];

    service.initFilterData = function(scope,type){
        //初始化默认数据
        $http.get(UrlMappings.SEARCH_PARAM_DEFAULT(type),{
            params : {
                'access_token':comutil.getTocken()
            },
            headers: {
                'Accept':'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function (data) {
            var defData = comutil.transcateData(data);
            // 默认的改成按字母分类了
            defData['cities'] = defData['cities'][''];

            for(var i in filterTypes){
                scope[filterTypes[i]] = defData[filterTypes[i]];
                if($.inArray(filterTypes[i],defTotal)>=0){
                    // 设置默认总体
                    for(var j in defData[filterTypes[i]]){
                        if(defData[filterTypes[i]][j].name=='总体'){
                            scope.formData[filterTypes[i]][defData[filterTypes[i]][j].id]=true;
                            break;
                        }
                    }
                }
            }
            if(!scope.$$phase) {
                scope.$apply();
            }
        }).error(function(data,status){
            if(status=='401')comutil.logout($state);
        });


        //scope['alphabetList'] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

        //受众地域初始化
        if($.isEmptyObject(cityInfo)){
            $http.get(UrlMappings.REGION_RESOURCE_LIST,{
                params : {
                    'access_token':comutil.getTocken()
                },
                headers: {
                    'Accept':'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (data) {
                cityInfo = data;
                scope['hotCities'] = data['hotCities'][''];
                scope['baseProviceCities'] = data['province'][''];
                scope['alphCities'] = data['city'];

                if(!scope.$$phase) {
                    scope.$apply();
                }
            }).error(function(data,status){
                if(status=='401')comutil.logout($state);
            });
        }else{
            scope['hotCities'] = cityInfo['hotCities'][''];
            scope['baseProviceCities'] = cityInfo['province'][''];
            scope['alphCities'] = cityInfo['city'];
        }

        scope['starDetails'] = {};

        if($.isEmptyObject(starsInfo)) {
            //明星初始化 分两次，提高响应速度
            $http.get(UrlMappings.STAR_RESOURCE_LIST, {
                params: {
                    'access_token': comutil.getTocken()
                },
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            }).success(function (data) {
                //缓存起来
                starsInfo = data;

                // 对明星顺序排序
                /*for (var key in data) {
                    scope['starDetails'][key] = {};
                }*/

                for (var i in starsKey) {
                    if(starsInfo[starsKey[i]]==undefined||starsInfo[starsKey[i]]==null)continue;
                    scope['starDetails'][starsKey[i]] = {};
                }

                if (!scope.$$phase) {
                    scope.$apply();
                }
            }).error(function(data,status){
                if(status=='401')comutil.logout($state);
            });

        }else{
           /* for (var key in starsInfo) {
                scope['starDetails'][key] = {};
            }*/
            for (var i in starsKey) {
                if(starsInfo[starsKey[i]]==undefined||starsInfo[starsKey[i]]==null)continue;
                scope['starDetails'][starsKey[i]] = {};
            }
        }

    };

    //缓存明星信息
    var starsKey = ['大陆男星','大陆女星','大陆组合','大陆其他','日韩男星','日韩女星','日韩组合','日韩其他','欧美男星'
        ,'欧美女星','欧美组合','欧美其他','港澳台/东南亚男星','港澳台/东南亚女星','港澳台/东南亚组合','港澳台/东南亚其他'
        ,'其他地区男星','其他地区女星','其他地区组合'];
    var starsInfo = {};
    //缓存城市信息
    var cityInfo = {};

    service.getStarDetail = function(starType){
        return starsInfo[starType];
    };

    var formatWeekDate = function(strdate){
        var tmpStarts = strdate.split('~');
        tmpStarts[0] = new Date(tmpStarts[0]);
        var tmpStartYear = tmpStarts[0].getFullYear();
        tmpStarts[1] = new Date(tmpStartYear+'/'+tmpStarts[1]);
        if(tmpStarts[1].getTime()<tmpStarts[0].getTime()){
            tmpStarts[1] = new Date(tmpStarts[1].getFullYear()+1,tmpStarts[1].getMonth(),tmpStarts[1].getDate());
        }
        return tmpStarts[0].Format("yyyyMMdd")+'-'+tmpStarts[1].Format("yyyyMMdd");
    };

    service.proFormDetail = function(formData,queryType){

        if(formData['startTime'].indexOf('~')>=0){
            formData['isWeek'] = 1;//周
            formData['startTime'] = formatWeekDate(formData['startTime']);
            formData['endTime'] = formatWeekDate(formData['endTime']);

        }else{
            formData['isWeek'] = 0;
            formData['startTime'] = new Date(formData['startTime']).Format("yyyyMMdd");
            formData['endTime'] = new Date(formData['endTime']).Format("yyyyMMdd");
        }

        formData['queryType'] = queryType;

        formData['pageNo'] = 1;
        formData['pageSize'] = 50;

        //产生uuid
        formData['uuid'] = generateUUID();

        var tmpData = comutil.recDatatoSubmit(formData);

        return tmpData;
    };


    return service;
}]);